/*
 * @Author: AiLjx
 * @Date: 2022-06-11 11:18:27
 * @LastEditors: AiLjx
 * @LastEditTime: 2022-06-29 22:54:16
 */
/**
 * 使用useContext将useReducer全局状态分发出去
 */

import React, { useContext, useReducer } from "react";

const initialState = {
    a: 0,
    b: 0,
};

function reducer(state, action) {
    let nextState = { ...state };
    switch (action.type) {
        case "putA":
            nextState.a++;
            return nextState;
        case "putB":
            nextState.b = action.value;
            return nextState;
        default:
            return nextState;
    }
}

const GlobalContext = React.createContext();

export default function App() {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (
        <GlobalContext.Provider value={{ state, dispatch }}>
            <Child1></Child1>
            <Child2></Child2>
            <Child3></Child3>
        </GlobalContext.Provider>
    );
}

function Child1() {
    const { dispatch } = useContext(GlobalContext);
    return (
        <div>
            <button onClick={() => dispatch({ type: "putA" })}>修改a</button>
            <button
                onClick={() =>
                    dispatch({ type: "putB", value: "自定义修改内容" })
                }>
                修改b
            </button>
        </div>
    );
}
function Child2() {
    const { state } = useContext(GlobalContext);
    return <div>child1--状态a：{state.a}</div>;
}
function Child3() {
    console.log("Child3");
    const { state } = useContext(GlobalContext);
    return <div>child1--状态b：{state.b}</div>;
}
